package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.UnLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class UnLikesBehaviorServiceImpl implements UnLikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult unLike(UnLikesBehaviorDTO dto) {
        //获取用户登录信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        if (entry == null) {
            //entry == null 代表 UserId 与 EquipmentId 同时为null
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请使用账户或设备进行登录");
        }
        Query query = Query.query(Criteria.where("entryId").is(entry.getId())
                .and("articleId").is(dto.getArticleId()));
        if (dto.getType().equals(ApUnlikesBehavior.Type.UNLIKE.getCode())) {
            //0 不喜欢 查询mongoDB 是否存在不喜欢的集合数据
            ApUnlikesBehavior behavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
            if (behavior != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "您已设置不喜欢");
            }
            //不存在,添加数据
            ApUnlikesBehavior apUnlikesBehavior = ApUnlikesBehavior
                    .builder().articleId(dto.getArticleId()).entryId(entry.getId()).type(ApUnlikesBehavior
                            .Type.UNLIKE.getCode()).createdTime(new Date()).build();
            mongoTemplate.save(apUnlikesBehavior);
        } else {
            //1 取消不喜欢
            mongoTemplate.remove(query, ApUnlikesBehavior.class);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
